import { createSlice } from "@reduxjs/toolkit";
import { getContent, postContent } from "@/service/api.js";
const initialState = {
  title: "我是counter状态管理",
  counter: 0,
  list: [],
  name: "",
};
export const counterSlice = createSlice({
  name: "counterStore",
  initialState: { ...initialState },
  reducers: {
    add(state) {
      state.counter++;
    },
    sub(state, action) {
      state.counter -= action.payload;
    },
    setState(state, action) {
      Object.keys(action.payload).forEach((key) => {
        state[key] = action.payload[key];
      });
    },
    reSetState(state) {
      const newState = { ...initialState };
      Object.keys(newState).forEach((key) => {
        state[key] = newState[key];
      });
    },
  },
  extraReducers: (builder) => {
    builder
      .addCase(getContent.fulfilled, (state, action) => {
        console.log(action, "ac===========");
        const res = action.payload;
        if (res && res?.code === 200) {
          state.list = res.data.arrList;
        }
      })
      .addCase(postContent.fulfilled, (state, action) => {
        console.log(action, "cccccccccccccccccccccccccccc");
        const res = action.payload;
        if (res && res?.code === 200) {
          state.name = res.data;
        }
      });
  },
});

export const { add, sub, reSetState } = counterSlice.actions;
export default counterSlice.reducer;
